<?php
namespace control;
/*
*档案管理类
*/


class dossierClass extends adIndexClass
{
	private const page       = 'dossier';      # 权限
	private const table      = 'archive_file'; # 数据表
	private const table_type = 'archive_type'; //分类表
	private const title      = '档案管理';

	public static function getDepartmentAll($data = []): string
	{
		// 条件
		$data['where'] = $data['where'] ?? "pid='0'";
		// 点击事件
		$data['click'] = $data['click'] ?? "replaceContent(this,'" . self::page . "')";
		// 结果
		$result = find(['table' => self::table_type, 'where' => $data['where'] . " order by list asc"]);
		$style  = ($data['where'] == "pid='0'") ? '' : ' class="child-node"';
		$temp   = "<ul {$style} {$data['where']}>";
		$textcontent_ico = "<span class='textcontent_ico'></span>";
		if ($result['array']) {
			foreach ($result['array'] as $value) {
				// 角标
				$arrow = "<span class='arrow'  onclick=\"liZoom($(this).parent())\"></span>";
				// 判断下级是否存在
				$data['where'] = " pid='{$value['id']}' ";
				$has           = query(self::table_type, $data['where']);
				$dots          = "<div class='actionBlock none'>
                                        <img data-pid='{$value['pid']}' title='添加同级' onclick=\"layer('" . self::page . "','catalog',{id:'" . suiji() . "',pid:'{$value['pid']}'})\" src='".root."img/control/list_copy.svg'>
                                        <img data-pid='{$value['pid']}' title='添加下级' onclick=\"layer('" . self::page . "','catalog',{id:'" . suiji() . "',pid:'{$value['id']}',type:'children'})\" src='".root."img/control/list_add.svg'>
                                        <img data-id='{$value['pid']}' title='编辑' onclick=\"layer('" . self::page . "','catalog',{id:'" . $value['id'] . "'})\" src='".root."img/control/edit.svg'>
                                        <img data-id='{$value['pid']}' title='删除' onclick=\"layer('" . self::page . "','operate',{'act': 'delType',id:'" . $value['id'] . "'})\" src='".root."img/control/list_del.svg'>
                                    </div>";
				if ($has['id']) {
					$temp .= "<li class='arrow-li' data-id='{$value['id']}' onclick=\"{$data['click']}\">
                                {$arrow}
                                <span class='textcontent'>{$textcontent_ico}{$value['name']}</span>
                                <div class='action-div'>{$dots}</div>
                            </li>";
					$temp .= self::getDepartmentAll($data);
				} else {
					$temp .= "<li class='arrow-no-li'  data-id='{$value['id']}' onclick=\"{$data['click']}\">
                                <span class='textcontent'>{$textcontent_ico}{$value['name']}</span>
                                <div class='action-div'>{$dots}</div>
                            </li>";
				}
			}
		}
		$temp .= '</ul>';
		return $temp;
	}

	/**
	 * 异步加载
	 */
	public function homeRightJson(): bool|string
	{
		$json['html'] = $this->homeRight();
		return json_encode($json, 320);
	}

	public function homeRightJsonSearch(): bool|string
	{
		return $this->homeSearch();
	}

	/**
	 * 左侧搜索框
	 *
	 * @return string
	 */
	public function getContainerLeftJson(): string
	{
		$option['click'] = 'replaceContent(this, \'dossier\')';
		$json['html']    = self::getDepartmentAll($option);
		return json_encode($json, 320);
	}

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'typeId'      => [
                        'name'  => "分类",
                        'width' => 100,
                    ],
                    'fileBtn' => [
                        'name'  => "附件数量",
                        'width' => 100,
                    ],
                    'serialStr'  => [
                        'name'  => "全宗号",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'department'         => [
                        'name'  => '部门名称',
                        'width' => 100,
                    ],
                    'orderNo'          => [
                        'name'  => '归档号',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'archiveYear'          => [
                        'name'  => '归档年度',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'name'          => [
                        'name'  => '题名',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'pageNum'          => [
                        'name'  => '页数',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'partNum'          => [
                        'name'  => '份数',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'fileDate'          => [
                        'name'  => '文件形成日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'level'          => [
                        'name'  => '密级',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'stid'          => [
                        'name'  => '归档人',
                        'width' => 100,
                    ],
                    'archiveDate'          => [
                        'name'  => '归档日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'locationId'          => [
                        'name'  => '存放位置',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }


	/*列表页-查询条件*/
	public function home()
	{
		//返回
		$rightHtml       = $this->homeRight();
		$option['click'] = 'replaceContent(this, \'dossier\')';
		$all             = self::getDepartmentAll($option);
        $html            = componentClass::leftNav([
            'title'=>'搜索分类',
            'click'=>$option['click'],
            'edit'=>1,
            'allTitle'=>'全部分类',
            'button'=>"<img class='tool-img' title='添加分类' onclick=\"layer('" . self::page . "','catalog',{id:'" . suiji() . "', pid: 0})\" src='".root."img/control/list_add.svg'>",
            'all'=>$all,
            'rightHtml'=>$rightHtml,
        ]);
        $html            .= <<<EOT
<style>
.container-main .container-left .action-div {width: 100px!important;margin-left: 5px;}
.container-main .container-left .classify-area .actionBlock {width: 100px!important;}
</style>
EOT;
		//返回
		return $this->homeFun($html);
	}

	public function catalog(): bool|string
	{
		//数据查询
		$info = query(self::table_type, " id = '" . $this->post('id') . "' ");
		$pid  = $info['pid'] ?: ($this->post('pid') ?: '0');
		//表单
		$html = $this->layerEdit([
			"table" => [
				[
					must . "分类：" => text(["name" => "name", "value" => $info['name'], 'class' => 'text']),
				],
				[
					"排序号：" => text(["name" => "list", "value" => $info['list'], 'class' => 'text']) . hidden(['name' => 'pid', 'value' => $pid]),
				],
			],
		]);
		//返回
		return $this->layer(["title" => "编辑分类", "height" => 220, "html" => $html]);
	}

	public function catalogEdit(): bool|string
	{
		$id = $this->post('id') ?: self::getId();
		//赋值
		$field = [
			'pid'  => $this->post('pid') ?: '0',
			"name" => $this->post('name'),      //部门名称
			"list" => $this->post('list'),      //排序号
		];
		$info  = query(self::table_type, " id = '" . $id . "' ");
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑的权限";
		} elseif (empty($field['name'])) {
			$json['warn'] = "请填写分类名称";
		} elseif (static::total(array('table' => self::table_type, 'where' => "id !='$id' and name = '$field[name]' and pid = '$field[pid]'")) > 0) {
			$json['warn'] = "已经存在此分类名称";
		} elseif (empty($info['id'])) {
			$field        = array_merge($field, ["id" => $id]);
			$json['warn'] = insert(["table" => self::table_type, "field" => $field]);
		} else {
			$json['warn'] = update(["table" => self::table_type, "field" => $field, "where" => "id = '" . $id . "'"]);
		}
		if (in_array($json['warn'], array("新增成功", "更新成功"))) {
			//添加日志
			$type = mb_substr($json['warn'], 0, 2, 'utf-8');
			$text = $this->control['name'] . $type . "了一个分类：" . $field['name'];
			$this->logText(array("type" => self::page, "text" => $text));
			//提示
			$_SESSION['warn'] = $json['warn'];
			$json['warn']     = 2;
		}
		//返回
		return json_encode($json, 320);
	}

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $typeId = $this->post('objId') ?? null;
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "归档号" => text(array("name" => "orderNo")).hidden(array('name' => 'typeId', 'value' => $typeId)),
                    "全宗号"     => select(array('name' => 'serialStr', 'option' => explode(',', para('serialStr')))),
                    '部门名称' => selectMultiple(array("name" => "departmentId", 'table' => "department", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200')),
                ],
                [
                    '归档年度'   => text(array('name' => 'archiveYear', 'laydate' => ['type' => 'year'])),
                    "保管期限" => select(array('name' => 'saveTime', 'option' => explode('，', para('archiveSaveTime')))),
                    '题名'   => text(array("name" => "name")),
                ],
                [
                    "密级" => select(array("name" => "secretLevel", "option" => explode('，', para('secretLevelOption')))),
                    "归档日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "存放位置" => selectMultiple(array("name" => "locationId", 'table' => "archive_cabinet", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200')),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

	public function homeRight()
	{
        $html = $this->homeOptions(false);
        $typeId = $this->post('objId') ?? null;
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit") && $typeId) {
            $button .= "<span onclick=\"layer('".self::page."','edit', {'typeId': '{$typeId}'})\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "print")) {
            $button .= "<span onclick=\"toPrint('listForm')\" class='spanButton'>打印</span>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','chooseCabinet',{})\" class='spanButton'>入库</span>\n";
            $button .= "<span onclick=\"addBorrow()\" class='spanButton'>加入待借</span>\n";
            $button .= "<span onclick=\"addRuin()\" class='spanButton'>加入销毁</span>\n";
        }
		//返回
		return $this->search($html,layout: 'pop',toolButton: $button);
	}


	public function homeSearch(): bool|string
	{
		$typeId = $this->post('typeId');
		$like   = array(
			"orderNo" => $this->post('orderNo'),//名称
			"name"    => $this->post('name'),
		);
		//全等查询数组
		$equal = array(
			"serialStr"    => $this->post('serialStr'),//状态
			"typeId"       => $this->post('typeId'),//类型
			"departmentId" => $this->post('departmentId'),
			"archiveYear"  => $this->post('archiveYear'),
			"saveTime"     => $this->post('saveTime'),
			"secretLevel"  => $this->post('secretLevel'),
			"locationId"   => $this->post('locationId'),
		);
		$and   = "and fileState !=2";
		if ($this->post('createTime')) {
			$and .= self::timeComparison($this->post('createTime'), field: 'archiveDate');
		}
		if (!$this->power(self::page, 'seeAll')) {
			$and .= " and stid = '" . self::$stid . "'";
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		//获取查询结果
		$where = search(array("like" => $like, "=" => $equal)) . $and;

		$page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));

		$_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate   = array(
				"box"    => array("name" => "listId", "value" => $array['id']),
				'edit'   => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{typeId:'" . $array['typeId'] . "', id:'" . $array['id'] . "'})"),
				"detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
			);
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "typeId":
                        $row[] = self::getTypeName($array['typeId']);
                        break;
                    case "fileBtn":
                        if ($array['source'] == '归档管理') {
                            $archive = query('archive', "id = '$array[sourceId]'");
                            $num     = static::total(array('table' => 'file', 'where' => "targetId = '" . $archive['targetId'] . "'"));
                            $fileBtn = $num > 0 ? "<span class='link' onclick=\"layer('component','fileDetail',{id:'" . $archive['targetId'] . "'})\">" . $num . "</span>" : '';
                        } else {
                            $num     = static::total(array('table' => 'file', 'where' => "targetId = '" . $array['id'] . "'"));
                            $fileBtn = $num > 0 ? "<span class='link' onclick=\"layer('component','fileDetail',{id:'" . $array['id'] . "'})\">" . $num . "</span>" : '';
                        }
                        $row[] = $fileBtn;
                        break;
                    case "department":
                        $department = query('department', "id = '$array[departmentId]'");
                        $row[] = $department['name'];
                        break;
                    case "locationId":
                        $row[] = self::getPosititonName($array['locationId']);
                        break;
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(partNum),0) as partNum",
        ]);
        $total    = [
            'partNum'        => $totalQuery['partNum'],
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 150),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
		//返回
		$json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		$json['html'] .= $this->homeJs();

		return json_encode($json, 320);
	}

	/**
	 * 打印
	 * @return string
	 */
	public function printPage(): string
	{
		$idArr = $this->get('ids') ? explode(',', $this->get('ids')) : [];
		$data  = [];
		foreach ($idArr as $id) {
			$info   = query(self::table, "id = '$id'");
			$data[] = [
				'logo'        => $this->root . 'img/svg/adloginIco.svg',
				'orderNo'     => $info['orderNo'],
				'type'        => self::getTypeName($info['typeId']),
				'location'    => self::getPosititonName($info['locationId']),
				'archiveDate' => $info['archiveDate'],
				'name'        => $info['name'],
			];
		}
		return (new printTemplateClass())->start(self::page, $data);
	}

	/**
	 * 样式
	 */
	public function style(): string
	{
		return <<<efo
<style>
.card-qr-box{width: 371px}
.card-qr-img .logo{height: 59.5px}
.card-qr-img{height: 150px}
</style>
efo;
	}

	public function homeJs(): string
	{
		return <<<eof
<script>
function toPrint(formName){
    let arr = [];
    $("[name='" + formName + "'] input[type=checkbox]:checked").each(function () {
        if ($(this).val() && $(this).val() !== 'on') {
            arr.push($(this).val());
        }
    });
    let vals = arr.join(",");
    if (!vals){
        msg('请选择需要打印的数据','error')
    }else{
         window.open(root+'control/adIndex.html?cla=dossier&fun=printPage&ids='+vals)
    }
}
function addBorrow(){
     let arr = [];
    $("[name='listForm'] input[type=checkbox]:checked").each(function () {
        if ($(this).val() && $(this).val() !== 'on') {
            arr.push($(this).val());
        }
    });
    if (arr.length > 0) {
        let vals = arr.join(",");
        newIframe('档案借阅详情',root+'control/adIndex.html?cla=archiveBorrow&fun=edit&source=dossier&listId='+vals)
    } else {
        msg('请选择需要加入待借的档案','error');
    }
}
function addRuin(){
     let arr = [];
    $("[name='listForm'] input[type=checkbox]:checked").each(function () {
        if ($(this).val() && $(this).val() !== 'on') {
            arr.push($(this).val());
        }
    });
    if (arr.length > 0) {
        let vals = arr.join(",");
        newIframe('档案销毁详情',root+'control/adIndex.html?cla=archiveRuin&fun=edit&source=dossier&listId='+vals)
    } else {
        msg('请选择需要加入销毁的档案','error');
    }
}

//分类下拉菜单页面
$(".dots").click(function(event) {
    $(".stateBlock").hide();
    let obj = $(this).find(".stateBlock");
      let state = obj.css('display');
    if (state == 'block') {
        obj.hide();
    } else {
        obj.show();
    }
　　　event.stopPropagation()
})
 //点击非下拉区域隐藏
$(document).bind('click', function (e) {
    let target = $(".stateBlock");
    if(!target.is(e.target) && target.has(e.target).length ===0){
      clearDiv();
    }
});
 function clearDiv(){
      $(".stateBlock").hide();
 }
 function confirmCabinet(e){
       let id = $(e).data('id');
       $("[name='cabinetId']").val(id);
       $(".paper-content-block").find("li").css('background-color','white')
       $(e).css('background-color','rgba(215, 215, 215, 0.698)')
 }
</script>
eof;
	}


	/**
	 * 入库
	 */
	public function confirmCabinet(): bool|string
	{
		$locationId = $this->post('cabinetId');
		$listId     = $this->post('dossierId') ? [$this->post('dossierId')] : $this->post('listId');
		$cabinet    = query('archive_cabinet', "id = '$locationId'");
		if (empty($locationId)) {
			$json['warn'] = '请先选择库位';
		} elseif (static::is_null_array($listId)) {
			$json['warn'] = '请选择档案';
		} elseif (empty($cabinet['id'])) {
			$json['warn'] = '请选择库位';
		} else {
			$x    = 0;
			$text = '';
			foreach ($listId as $id) {
				$info = query(self::table, "id = '$id'");
				if (!empty($info['id'])) {
					$warn = static::update(array(
						'table' => self::table,
						'field' => [
							'locationId' => $locationId,
						],
						'where' => "id = '$info[id]'",
					));
					if ($warn == '更新成功') {
						$x++;
						$text .= "归档号【{$info['orderNo']}】成功<br>";
					} else {
						$text .= "归档号【{$info['orderNo']}】失败：更新失败<br>";
					}
				}
			}
			if ($text) {
				$text = $this->control['name'] . "更新档案库位：" . $text;
				$this->logText(["type" => self::page, "text" => $text]);
			}
			$json['warn']     = 2;
			$_SESSION['warn'] = '成功入库了' . $x . '个档案，详情请查看系统日志';
		}
		return json_encode($json, 320);
	}

	/**
	 * 选择库位
	 */
	public function chooseCabinet(): bool|string
	{
		$all  = self::archive_cabinet();
		$id   = $this->post('id');
		$html = <<<efo
                    <div class="container-left paper-content-block" id="container-left" style="display: block;">
                       {$all}
                    </div>
                    <form name="locationForm"><input type="hidden" name="cabinetId" value=""><input type="hidden" name="dossierId" value="$id"></form>
                    <div style="position:absolute;bottom: 30px;right: 30px"><span class="spanButton" onclick="$('#dossierChooseCabinet').hide()">取消</span><span class="spanButton li-btn-blue-bg" onclick="subForm('locationForm,listForm',root+'control/adIndex.html?cla=dossier&fun=confirmCabinet')">确定</span></div>
<style>
 .paper-content-block{width: 90%;height: auto;background-color: white;min-height: unset;min-width: unset;padding: 20px;}
</style>
efo;

		return $this->layer(array("title" => "选择库位", "height" => 500, "width" => 600, "html" => $html, "button" => false));
	}

	public static function archive_cabinet($data = []): string
	{
		// 条件
		$data['where'] = $data['where'] ?? "pid='0'";
		// 点击事件
		$data['click'] = $data['click'] ?? "replaceDetail($(this).parent(),'dossier')";
		// 结果
		$result = find(['table' => 'archive_cabinet', 'where' => $data['where'] . " order by list asc"]);
		$style  = ($data['where'] == "pid='0'") ? '' : ' class="child-node"';
		$temp   = "<ul {$style} {$data['where']}>";
		// 角标

		if ($result['array']) {
			foreach ($result['array'] as $value) {
				// 角标
				$arrow = "<span class='arrow'  onclick=\"{$data['click']}\"></span>";
				// 判断下级是否存在
				$data['where'] = " pid='{$value['id']}' ";
				$has           = query('archive_cabinet', $data['where']);
				if ($has['id']) {
					$temp .= "<li class='arrow-li' data-id='{$value['id']}' data-name='{$value['name']}'  onclick=\"confirmCabinet(this)\">{$arrow}{$value['name']}</li>";
					$temp .= self::archive_cabinet($data);
				} else {
					$temp .= "<li class='arrow-no-li'  data-id='{$value['id']}' data-name='{$value['name']}' onclick='confirmCabinet(this)'>{$value['name']}</li>";
				}
			}
		}
		$temp .= '</ul>';
		return $temp;
	}


	/**
	 * 导出
	 */
	public function exportData()
	{
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
		if (!$this->power(self::page, 'export')) {
			$_SESSION['warn'] = '你还没有导出的权限';
        }  else {
			$data   = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $type         = self::getTypeName($array['typeId']);
                $transferDept = query('department', "id = '$array[transferDept]'");
                $department   = query('department', "id = '$array[departmentId]'");
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '分类'=>$type,
                            '归档号'=>$array['orderNo'],
                            '全宗号'=>$array['serialStr'],
                            '部门名称'=> $department['name'],
                            '移交人'=> self::findStaff($array['transferStid']),
                            '移交部门'=> $transferDept['name'],
                            '题名'=>$array['name'],
                            '文号'=>$array['preText'],
                            '归档年度'=>$array['archiveYear'],
                            '保管期限'=>$array['saveTime'],
                            '文件形成日期'=>$array['fileDate'],
                            '密级'=>$array['level'],
                            '页数'=>$array['pageNum'],
                            '份数'=>$array['partNum'],
                            '归档日期'=>$array['archiveDate'],
                            '存放位置'=>self::getPosititonName($array['locationId']),
                            '备注'=>$array['text'],
                            '创建日期'=>$array['time'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
			$text = $this->control['name'] . "导出了".self::title;
			$this->logText(["type" => self::page, "text" => $text]);
			$this->excelOut($title, $data, self::title.".xlsx");
            exit(0);
		}
		header("Location:" . getenv("HTTP_REFERER"));
	}

	/**
	 * 下载模板
	 */
	public function downloadModel()
	{
        $templateId = $this->get('templateId');
		if (!$this->power(self::page, 'edit')) {
			$_SESSION['warn'] = '你还没有编辑的权限';
        } else {
            $exampleData[] = ['公文>通知', '雨木科技', '总经办', '张三', 'YM202111220001', '总经办', '通知', '雨木文[2022]01', '2022', '永久', '2022-01-01', '内部', 1, 1, '2021-01-01', '默认库位', '样例数据，导入时请删除此条数据'];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '分类'=>$example[0],
                            '全宗号'=>$example[1],
                            '部门名称'=>$example[2],
                            '移交人'=>$example[3],
                            '移交人编号'=>$example[4],
                            '移交部门'=>$example[5],
                            '题名'=>$example[6],
                            '文号'=>$example[7],
                            '归档年度'=>$example[8],
                            '保管期限'=>$example[9],
                            '文件形成日期'=>$example[10],
                            '密级'=>$example[11],
                            '页数'=>$example[12],
                            '份数'=>$example[13],
                            '归档日期'=>$example[14],
                            '存放位置'=>$example[15],
                            '备注'=>$example[16],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
			$text   = $this->control['name'] . "下载了档案导入模板";
			$this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
			exit(0);
		}
		header("Location:" . getenv("HTTP_REFERER"));
	}

	/*数据导入分析*/
	public function importData()
	{
        $templateId = $this->post('templateId');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑的权限';
        }  else {
			 $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
			$x    = 0;
			$text = '';
            $headArray = [];
            $row_list=0;
			foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
				if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
					//多级分类分割
					$typeArr = explode("&gt;", $cell['分类']?:'默认分类');
					if (is_array($typeArr)) {
						$pid = '0';
						foreach ($typeArr as $name) {
							$type = query(self::table_type, "name = '$name' and pid = '$pid'");
							if (empty($type['id'])) {
								$typeField = [
									'id'   => self::getId(),
									'pid'  => $pid ?: '0',
									"name" => $name,      //部门名称
									"list" => 1,      //排序号
								];
								insert(array('table' => self::table_type, "field" => $typeField));
								$pid        = $typeField['id'];
								$type['id'] = $typeField['id'];
							} else {
								$pid = $type['id'];
							}
						}
					}

					$staff        = query('staff', "orderNo = '$cell[移交人编号]' and state != '离职'");
					$department   = query('department', "name = '$cell[部门名称]'");
					$transferDept = query('department', "name = '$cell[移交部门]'");
					$location     = query('archive_cabinet', "name = '$cell[存放位置]'");
					$field        = [
						'id'           => self::getId(),
						'typeId'       => $type['id'] ?? '',
						"orderNo"      => archiveClass::archiveOrderNo($department['id'], $cell['全宗号']),
						"serialStr"    => $cell['全宗号'],
						'departmentId' => $department['id'],
						"transferStid" => $staff['id'],
						"transferDept" => $transferDept['id'],
						"name"         => $cell['题名'],
						"preText"      => $cell['文号'],
						"archiveYear"  => $cell['归档年度'],
						"saveTime"     => $cell['保管期限'],
						"fileDate"     => $cell['文件形成日期'],
						"level"        => $cell['密级'],
						"pageNum"      => $cell['页数'],
						"partNum"      => $cell['份数'],
						"archiveDate"  => $cell['归档日期'],
						"locationId"   => $location['id'],
						"text"         => $cell['备注'],
						"source"       => '导入',
						'stid'         => self::$stid,
					];
					$annotation   = [
						'orderNo'      => '归档号',
						'name'         => '题名',
						'serialStr'    => '全宗号',
						'departmentId' => '部门名称',
					];
					$rules        = [
						'orderNo'      => 'required',
						'name'         => 'required',
						'serialStr'    => 'required',
						'departmentId' => 'required',
					];
					// 校验是否符合规则
					$vt     = new \verify();
					$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
					if ($result === false) {
						$text .= "第【{$row_list}】行：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
					} elseif (static::total(array('table' => self::table, 'where' => " and orderNo = '$field[orderNo]'  and id !='$field[id]'")) > 0) {
						$text .= "第【{$row_list}】行导入失败：已存在此归档号的档案<br>";
					} elseif (!in_array($field['serialStr'], explode('，', para('serialStr')))) {
						$text .= "第【{$row_list}】行导入失败：此全宗号不在系统参数中<br>";
					} elseif (!in_array($field['level'], explode('，', para('secretLevelOption')))) {
						$text .= "第【{$row_list}】行导入失败：此密级类型不在选项中<br>";
					} elseif (!empty($cell[4]) && empty($staff['stid'])) {
						$text .= "第【{$row_list}】行导入失败：未找到此移交人<br>";
					} else {
						$location            = query('archive_cabinet', "isDefault = 0");
						$archive_type        = query('archive_type', "isDefault = 0");
						$field['locationId'] = $location['id'];
						$field['typeId']     = $archive_type['id'];
						$warn                = insert(["table" => self::table, "field" => $field]);
						if (in_array($warn, ["新增成功", "更新成功"])) {
							$x++;
							$text .= "第【{$row_list}】行数据导入成功<br>";
						} else {
							$text .= "第【{$row_list}】行导入失败：编辑失败<br>";
						}
					}
				}
			}
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
			$text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
			$this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
	}


	/**
	 * 启用/停用
	 */
	public function stateSwitch(): bool|string
	{
		$type = $this->post('type');
		//生成表单
		$html = $this->layerEdit(array(
			"table"     => array(
				array(
					"提示：" => "是否修改所选数据状态为：" . $type,
				),
			), 'hidden' => hidden(array('name' => 'type', 'value' => $type)),
		));
		//返回
		return $this->layer(array("title" => "状态切换", "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
	}

	/**
	 * 启用/停用
	 */
	public function stateSwitchEdit(): bool|string
	{
		$idArr = $this->post('id') ? [$this->post('id')] : $this->post('listId');
		$state = $this->post('type');
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有" . self::title . "的编辑权限";
		} elseif (empty($idArr) || !is_array($idArr)) {
			$json['warn'] = "请选择数据";
		} elseif (!in_array($state, ['启用', '停用'])) {
			$json['warn'] = "类型错误";
		} else {
			$field        = [
				'state' => $state,
			];
			$json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id in ('" . implode("','", $idArr) . "')"));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "的状态为【{$state}】， id：【" . implode(",", $idArr) . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
			}
		}
		//返回
		return json_encode($json, 320);
	}

	/**
	 * 获取分类名称
	 *
	 * @param $id
	 * @return mixed
	 */
	public static function getTypeName($id): mixed
	{
		$type = query(self::table_type, "id = '$id'");
		if (!empty($type['pid'])) {
			$result = self::getTypeName($type['pid']);
			$name   = $result . '->' . $type['name'];
		} else {
			$name = $type['name'] ?? null;
		}
		return $name;
	}

	/**
	 * 获取库位名称
	 *
	 * @param $id
	 * @return mixed
	 */
	public static function getPosititonName($id): mixed
	{
		$type = query('archive_cabinet', "id = '$id'");
		if (!empty($type['pid'])) {
			$result = self::getPosititonName($type['pid']);
			$name   = $result . '->' . $type['name'];
		} else {
			$name = $type['name'] ?? null;
		}
		return $name;
	}

	/*基本资料-弹出层*/
    public function edit()
    {
        $id       = $this->post('id') ?: self::getId();
        $info     = query(self::table, " id = '" . $id . "' ");
        if ($info['source'] == '归档管理') {
            $fileCollection = '';
            $hiden          = 'hide';
        } else {
            $hiden          = '';
            $fileCollection = fileUploadClass::addFileComponent($id, '档案管理', self::page, self::page . 'EditForm');
        }
        //表单
        $html = $this->layerEdit([
            "table" => [
                ["<div class='small-title'>基本信息</div>"],

                [
                    must . "分类：" => self::getTypeName($this->post('typeId')) . hidden(array('name' => 'typeId', 'value' => $this->post('typeId'))),
                    "归档号："       => $info['orderNo'],
                ],
                [
                    must . "全宗号："  => select(array('name' => 'serialStr', 'value' => $info['serialStr'], 'option' => explode(',', para('serialStr')), 'title' => '全宗号')),
                    must . "部门名称：" => selectMultiple(array("name" => "departmentId", 'value' => $info['departmentId'], "title" => "部门名称", 'table' => "department", 'sqlId' => 'id', 'sqlField' => 'name')),
                ],
                [
                    "移交人："  => selectMultiple(array("name" => "transferStid", 'value' => $info['transferStid'], "title" => "移交人", 'table' => "staff", 'where' => "state !='离职'", 'sqlId' => 'stid', 'sqlField' => 'name')),
                    "移交部门：" => selectMultiple(array("name" => "transferDept", 'value' => $info['transferDept'], "title" => "部门名称", 'table' => "department", 'sqlId' => 'id', 'sqlField' => 'name')),
                ],
                [
                    "移交日期：" => text(array('name' => 'transferDate', 'value' => $info['transferDate'], 'laydate' => [])),
                ],
                [
                    must . "题名：" => text(["name" => "name", 'class' => 'text', "value" => $info['name']]),
                    "文号："        => text(["name" => "preText", 'class' => 'text', "value" => $info['preText']]),
                ],
                [
                    must . "归档年度：" => text(array('name' => 'archiveYear', 'value' => $info['archiveYear'] ?: date('Y'), 'laydate' => ['type' => 'year'])),
                    "保管期限："        => select(["name" => "saveTime", 'title' => '保管期限', 'option' => explode('，', para('archiveSaveTime')), "value" => $info['saveTime']]),
                ],
                [
                    "文件形成日期：" => text(array('name' => 'fileDate', 'value' => $info['fileDate'], 'laydate' => [])),
                    "密级："     => select(["name" => "level", 'title' => '密级', 'option' => explode('，', para('secretLevelOption')), "value" => $info['level']]),
                ],
                [
                    "页数：" => text(["name" => "pageNum", 'class' => 'text', "value" => $info['pageNum']]),
                    "份数：" => text(["name" => "partNum", 'class' => 'text', "value" => $info['partNum']]),
                ],
                [
                    "归档日期：" => text(["name" => "archiveDate", 'laydate' => [], 'class' => 'text', "value" => $info['archiveDate']]),
                    "存放位置：" => selectMultiple(array("name" => "locationId", 'value' => $info['locationId'], "title" => "存放位置", 'table' => "archive_cabinet", 'sqlId' => 'id', 'sqlField' => 'name')),
                ],
                [
                    "备注：" => textarea(["name" => "text", 'class' => 'textarea', "value" => $info['text']]),
                ],
                [
                    "<div class='small-title $hiden'>附件</div>",
                ],
                [
                    $fileCollection,
                ],
            ],
        ]);
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 700, "html" => $html));
    }


	/*异步处理*/
	public function editEdit(): bool|string
	{
		$fileId = $this->post('fileId') ?? [];
		$id     = $this->post('id') ?: self::getId();
		//赋值
		$field = [
			'typeId'       => $this->post('typeId'),
			"serialStr"    => $this->post('serialStr'),//物料编码
			"departmentId" => $this->post('departmentId'),
			"transferStid" => $this->post('transferStid'),
			'transferDept' => $this->post('transferDept'),
			'transferDate' => $this->post('transferDate'),
			"name"         => $this->post('name'),
			"preText"      => $this->post('preText'),
			"archiveYear"  => $this->post('archiveYear'),
			"saveTime"     => $this->post('saveTime'),
			"fileDate"     => $this->post('fileDate'),
			"level"        => $this->post('level'),
			"pageNum"      => $this->post('pageNum'),
			"partNum"      => $this->post('partNum'),
			"archiveDate"  => $this->post('archiveDate'),
			"locationId"   => $this->post('locationId'),
			"text"         => $this->post('text'),
		];

		$annotation = [
			'typeId'       => '分类',
			'serialStr'    => '全宗号',
			'name'         => '题名',
			'departmentId' => '部门',
			'archiveYear'  => '归档年度',
            "pageNum"      => '页数',
            "partNum"      => '份数',
		];
		$rules      = [
			'typeId'       => 'required',
			'serialStr'    => 'required',
			'name'         => 'required',
			'departmentId' => 'required',
			'archiveYear'  => 'required',
            "pageNum"      => 'numeric',
            "partNum"      => 'numeric',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			goto resp;
		}
		$info = query(self::table, " id = '" . $id . "' ");
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑部门的权限";
		} else {
			if (empty($field['locationId'])) {
				$location            = query('archive_cabinet', "isDefault = 0");
				$field['locationId'] = $location['id'];
			}

			if (empty($info['id'])) {
				$field        = array_merge($field, ["id" => $id, 'source' => '新增', 'orderNo' => archiveClass::archiveOrderNo($field['departmentId'], $field['serialStr']), 'stid' => self::$stid]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$json['warn'] = static::update(["table" => self::table, "field" => $field, "where" => "id = '" . $id . "'"]);
			}
			if (in_array($json['warn'], array("新增成功", "更新成功"))) {
				//更新文件
				update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileId) . "')"));
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了一个档案：" . $field['name'] . ",ID：" . $id;
				$this->logText(array("type" => self::page, "text" => $text));
				//提示
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . 'control/adIndex.html?cla=' . self::page . '&fun=detail&id=' . $id;
			}
		}
		//返回
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 明细
	 *
	 * @return bool|string
	 */
	public function detail(): bool|string
	{
		$info = query(self::table, " id = '" . $this->get('id') . "' ");
		if (empty($info['id'])) {
			$html = "未找到此" . self::title;
		} else {
			$data = [
				"id" => $info['id'],
			];
			//按钮
			$button = [];
			if ($this->power(self::page, "edit")) {
				$button[] = [
					"name"  => "编辑",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["typeId" => $info['typeId'], "id" => $info['id']],
					'style' => 'li-btn-blue-bg',
				];
				$button[] = [
					"name"  => '入库',
					"type"  => "点击事件",
					'title' => '入库',
					"fun"   => "layer('" . $this->get('cla') . "','chooseCabinet',{id:'" . $info['id'] . "'})",
				];
			}
			if ($this->power(self::page, 'del')) {
				$button[] = [
					"name" => "删除",
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'del', "id" => $info['id']],
				];
			}
			$department   = query('department', "id = '$info[departmentId]'");
			$transferDept = query('department', "id = '$info[transferDept]'");
			if ($info['source'] == '归档管理') {
				$archive        = query('archive', "id = '$info[sourceId]'");
				$fileCollection = fileUploadClass::showFile($archive['targetId']);
			} else {
				$fileCollection = fileUploadClass::showFile($info['id']);
			}

			$url    = urlencode($this->root . self::page . '?url=' . $info['orderNo']);
			$qrUrl  = $this->root . 'pay/wxpay/wxScanPng.php?url=' . $url;
			$qrHtml = '<div class="card-qr-box">
                            <div class="card-qr-img left">
                            	<img class="logo img-center" src="' . root . 'img/svg/adloginIco.svg" alt="adloginIco" width="102">
                            	<div class="card-qr-img-line"></div>
                                <img class="qr img-center" src="' . $qrUrl . '" alt="qr">
                            </div>
                            <div class="card-qr-ul left">
                                <p><span>&emsp;归档号：</span>' . $info['orderNo'] . '</p>
                                <p><span>&emsp;题&emsp;名：</span>' . $info['name'] . '</p>
                                <p><span>&emsp;分&emsp;类：</span>' . self::getTypeName($info['typeId']) . '</p>
                                <p><span>归档日期：</span>' . $info['archiveDate'] . '</p>
                                <p><span>&emsp;位&emsp;置：</span>' . self::getPosititonName($info['locationId']) . '</p>
                            </div>
                            </div>
                        </div>';
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow([
				"详细信息" => [
					[
						"分类"  => self::getTypeName($info['typeId']),
						"归档号" => $info['orderNo'],
						"全宗号" => $info['name'],
                        "部门名称" => $department['name'],
					],
					[
						"题名"   => $info['name'],
						"文号"   => $info['preText'],
						"归档年度" => $info['archiveYear'],
                        "保管期限"   => $info['saveTime'],
					],
					[

						"文件形成日期" => $info['fileDate'],
						"密级"     => $info['level'],
						"页数" => $info['pageNum'],
						"份数" => $info['partNum'],
					],
					[
						"备注" => $info['text'],
					],

				],
				'归档信息'   => [
					[
						"移交人"  => self::findStaff($info['transferStid']),
						"移交部门" => $transferDept['name'],
						"移交日期" => $info['transferDate'],
                        "归档人"  => self::findStaff($info['stid']),
					],
					[
						"归档日期" => $info['archiveDate'],
						"存放位置" => self::getPosititonName($info['locationId']),
					],
				],
				'附件'     => [
					[
						$fileCollection,
					],
				],
				'档案卡片'   => [
					[
						$qrHtml,
					],
				],
			]);
			//生成页面
			//生成页面
			$html = $this->tab($data) . $this->homeJs();
		}
		//返回
		return $html;
	}


	// 操作中转
	public function operate(): bool|string
	{
		$act  = $this->post('act') ?? '';
		$pwd  = false; // 需要密码
		$form = $power = $word = '';
		switch ($act) {
			case 'delType':
				$act      = 'del';
				$msg      = '删除分类';
				$title    = self::page . 'TypeDelete';
				$function = 'deleteType';
				$form     = self::page . 'OperateForm';
				$power    = '';
				break;
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除分类
	 *
	 * @return bool|string
	 */
	public function deleteType(): bool|string
	{
		$array = $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table_type, " id = '$id' ");
				if ($info['isDefault']) {
					$warn = "删除失败：此分类是默认分类";
				} elseif ($this->juagdeFile($id)) {
					$warn = "删除失败：此分类下存在档案";
				} else {
					//递归删除
					$this->deleteAll($id);
					//返回
					$warn = "删除成功";
					$x++;
				}
				$text .= "档案分类【" . $info['name'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了档案分类，结果如下：<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = "成功删除{$x}个档案分类，详情请查看日志";
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}

	/**
	 * 判断此分类或子分类下是否还存在物料
	 *
	 * @param $typeId
	 */
	public function juagdeFile($typeId): bool
	{
		$material_type = query(self::table_type, "pid = '$typeId'");
		if ($material_type['id']) {
			if (static::total(array('table' => self::table, 'where' => "typeId = '$typeId'")) > 0) {
				return true;
			} else {
				return $this->juagdeFile($material_type['id']);
			}
		} else {
			return false;
		}
	}

	public function deleteAll($id)
	{
		$material_type = query(self::table_type, "pid = '$id'");
		if ($material_type['id']) {
			$this->deleteAll($material_type['id']);
		}
		delete(array('table' => self::table_type, 'where' => "id = '$id'"));
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete(): bool|string
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " id = '$id' ");
				if ($info['fileState']) {
					$warn = "档案已借出或已销毁，暂不能删除";
				} else {
					if ($info['source'] == '归档管理') {
						update(array('table' => 'archive', 'field' => ['workFlow' => '待归档'], 'where' => "id = '$info[sourceId]'"));
					} else {
						$result = find(array('table' => 'file', 'where' => "targetId = '$id'"));
						foreach ($result['array'] as $file) {
							fileDelete($file['src']);
						}
						//删除附件
						delete(array("table" => "file", "where" => " targetId = '$id' "));
						//最后删除基本参数
						delete(array("table" => self::table, "where" => " id = '$id' "));
					}
					//返回
					$warn = "删除成功";
					//最后删除基本参数
					delete(array("table" => self::table, "where" => " id = '$id' "));
					$x++;
				}
				$text .= self::title . "题名【" . $info['name'] . "】，ID【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}
    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'分类',
                    'aliasName'=>'分类',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'全宗号',
                    'aliasName'=>'全宗号',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'部门名称',
                    'aliasName'=>'部门名称',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'移交人',
                    'aliasName'=>'移交人',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'移交人编号',
                    'aliasName'=>'移交人编号',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'移交部门',
                    'aliasName'=>'移交部门',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'题名',
                    'aliasName'=>'题名',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'文号',
                    'aliasName'=>'文号',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'归档年度',
                    'aliasName'=>'归档年度',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'保管期限',
                    'aliasName'=>'保管期限',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'文件形成日期',
                    'aliasName'=>'文件形成日期',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'密级',
                    'aliasName'=>'密级',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'页数',
                    'aliasName'=>'页数',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'份数',
                    'aliasName'=>'份数',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'归档日期',
                    'aliasName'=>'归档日期',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'存放位置',
                    'aliasName'=>'存放位置',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                    'isMust'=>false,
                ],
            ]
        };
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'分类',
                    'aliasName'=>'分类',
                ],
                [
                    'columnName'=>'归档号',
                    'aliasName'=>'归档号',
                ],
                [
                    'columnName'=>'全宗号',
                    'aliasName'=>'全宗号',
                ],
                [
                    'columnName'=>'部门名称',
                    'aliasName'=>'部门名称',
                ],
                [
                    'columnName'=>'移交人',
                    'aliasName'=>'移交人',
                ],
                [
                    'columnName'=>'移交部门',
                    'aliasName'=>'移交部门',
                ],
                [
                    'columnName'=>'题名',
                    'aliasName'=>'题名',
                ],
                [
                    'columnName'=>'文号',
                    'aliasName'=>'文号',
                ],
                [
                    'columnName'=>'归档年度',
                    'aliasName'=>'归档年度',
                ],
                [
                    'columnName'=>'保管期限',
                    'aliasName'=>'保管期限',
                ],
                [
                    'columnName'=>'文件形成日期',
                    'aliasName'=>'文件形成日期',
                ],
                [
                    'columnName'=>'密级',
                    'aliasName'=>'密级',
                ],
                [
                    'columnName'=>'页数',
                    'aliasName'=>'页数',
                ],
                [
                    'columnName'=>'份数',
                    'aliasName'=>'份数',
                ],
                [
                    'columnName'=>'归档日期',
                    'aliasName'=>'归档日期',
                ],
                [
                    'columnName'=>'存放位置',
                    'aliasName'=>'存放位置',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
                [
                    'columnName'=>'创建日期',
                    'aliasName'=>'创建日期',
                ],
            ]
        };
    }
}
